package com.ylyq.ylxx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ylyq.ylxx.constants.AccountConstant;
import com.ylyq.ylxx.service.IJinritemaiOauthService;
import com.ylyq.ylxx.service.IOauthService;
import com.ylyq.ylxx.util.HttpClientUtils;
import com.ylyq.ylxx.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OauthServiceImpl
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/6/23 17:28
 * @Version 1.0
 */
@Slf4j
@Service
public class JinritemaiOauthServiceImpl implements IJinritemaiOauthService {
    @Autowired
    private RedisUtil redisUtils;

    @Override
    public String getAccessToken(String userID, String auth_code) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.GET_ACCESS_TOKEN_Jinritemai.replace("#{CODE}",auth_code);

        String result = HttpClientUtils.post(open_api_url_prefix, "");
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("err_no");
        if (code==0) {
            JSONObject dataResult = JSONObject.parseObject(jsonObject.getString("data"));
            String access_token = dataResult.getString("access_token");
            String refresh_token = dataResult.getString("refresh_token");
            Integer token_expires_in = dataResult.getInteger("expires_in");
            //整个数据要不要存放到redis中？？？

            redisUtils.set("Jinritemai_access_token" + userID, access_token, token_expires_in);
            redisUtils.set("Jinritemai_refresh_token" + userID, refresh_token);
            return access_token;
        } else {
            log.error(jsonObject.getString("message"));
            return null;
        }
    }

    @Override
    public String reFreshAccessToken(String userID,String refreshToken) {
        // 请求地址
        String open_api_url_prefix = AccountConstant.Refresh_TOKEN_Jinritemai.replace("#{REFRESH_TOKEN}",refreshToken);

        String result = HttpClientUtils.post(open_api_url_prefix, "");
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("err_no");
        if (code==0) {
            JSONObject dataResult = JSONObject.parseObject(jsonObject.getString("data"));
            String access_token = dataResult.getString("access_token");
            String refresh_token = dataResult.getString("refresh_token");
            Integer token_expires_in = dataResult.getInteger("expires_in");
            //整个数据要不要存放到redis中？？？
            redisUtils.set("Jinritemai_access_token" + userID, access_token, token_expires_in);
            redisUtils.set("Jinritemai_refresh_token" + userID, refresh_token);
            return access_token;
        } else {
            log.error(jsonObject.getString("message"));
            return null;
        }
    }


}
